import 'package:path/path.dart';
import 'package:rs10000/common/net.dart';
import 'package:sqflite/sqflite.dart';

/*
sqflite: ^2.2.0
* */

class SQLite {

  static Database? _database;

  static Future<Database> get _db async {
    if (_database != null) return _database!;
    _database = await _initDB('chat.db');
    return _database!;
  }

  static Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);
    return await openDatabase(path, version: 1, onCreate: _createDB);
  }

  static Future _createDB(Database db, int version) async {
    const idType = 'INTEGER PRIMARY KEY AUTOINCREMENT';
    const textType = 'TEXT NOT NULL';
    const intType = 'INTEGER NOT NULL';
    await db.execute('''
      CREATE TABLE IF NOT EXISTS chat (
        id $idType,
        type $intType,
        sender $textType,
        senderName $textType,
        toUserId $textType,
        content $textType,
        data $textType,
        isRead $intType,
        timestamp $intType
      )
    ''');
  }

  static Future<void> insertMsg(NetMsg msg) async {
    await (await _db).insert('chat', {
      'type': msg.type,
      'sender': msg.sender,
      'senderName': msg.senderName,
      'toUserId': msg.toUserId,
      'content': msg.content,
      'data': msg.data,
      'isRead': msg.isRead?1:0,
      'timestamp': msg.timestamp,
    });
  }

  static Future<List<NetMsg>> selectAll(int type) async {
    List<Map<String, dynamic>> data = await (await _db).query('chat', where: 'type = $type', orderBy: 'timestamp DESC');//顺序 ASC 倒序 DESC
    List<NetMsg> chats = [];
    for (var item in data) {
      chats.add(NetMsg(item['type'], item['sender'], item['toUserId'], item['content'], item['timestamp'], item['isRead'] == 1, senderName: item['senderName'], data: item['data']));
    }
    return chats;
  }

  static Future<int> updateAll(int type) async {
    return (await (await _db).update('chat', {'isRead': 1}, where: 'type = $type'));
  }

  Future<void> delMsg(int id) async {
    await (await _db).delete('chat', where: 'id = ?', whereArgs: [id]);
  }

  static Future close() async {
    (await _db).close();
  }
}